# coding: utf-8
"""
Доработки:
- навесить исключения 
- добавить логгирование
- протестировать в продуктивной среде
- контроль выходных данных:
	повторяющиеся ключи (предупреждение)
	пробелы в ключах
"""
XLS_FILE_PATH = r'GAZ_Addition_Info_full.xls'
LOOKUP_FILE_PATH = r'GAZ_Addition_Info_full.txt'
NETCOOL_HOME = r'C:\IBM\tivoli\netcool\omnibus\bin\\'
PROBE_PA_NAME = 'EIF probe'
PA_NAME = "NCO_PA"
PA_USER = "repino"
PA_PASS = "AGFFBIBLFLFJFIGL" #зашифрован с помошью nco_g_crypt

import xlrd, codecs, re, os
def xls_to_lookup (xls_path, lookup_path = ' '):
	"""
	Generate lookup (tabbed) file from xls document
	"""
	if lookup_path == ' ':
		out_path = 'xls_to_lookup_out'
		if not os.path.exists (out_path):
			os.mkdir(out_path)
		lookup_path = os.getcwd() + "\\"+out_path+"\\lookup.txt"
	lookup_file = codecs.open(lookup_path, mode = "w", encoding = 'utf-8')
	xls_book = xlrd.open_workbook(xls_path, formatting_info=False)
	xls_sheet = xls_book.sheet_by_index(0)
	col_num = len(xls_sheet.row_values(0))
	is_first_string = True
	for row_index in range(xls_sheet.nrows):
		input_row = xls_sheet.row_values(row_index)
		input_row[0] = unicode(input_row[0]).upper() #преобразование ключевого поля
		output_row=[]
		for input_field in input_row:
			if type(input_field) == type(1.0):		#обработка чисел (могут храниться как float в xls ) - есть вероятность потерять остаток номера телефона
				input_field = "%.10f" % input_field
				input_field = input_field.replace('.', ', ')
				# написать более красивую обработку нулевых телефонов	
				input_field = input_field.replace('0000000000', '')
			output_field =re.sub(r'\s+', ' ', unicode(input_field)).strip()  #заменить всевозможные проблеьные символы пробелами и обрезать ведущие и замыкающие пробелы 
			if output_field:
				output_row.append(output_field)
		output_string = '\t'.join(output_row)
		if len(output_row) != col_num:
			print u"Ошибка! Имеются пустые поля в строке номер:%d\n%s\n" %(row_index+1, output_string)
		elif is_first_string:
			lookup_file.write(output_string)
			is_first_string = False
		else:
			lookup_file.write('\n'+output_string)
	lookup_file.close()
	return

def probe_status (probe_pa_name):
	"""
	Getting probe status  
	cmd example:
	C:\IBM\tivoli\netcool\omnibus\bin\nco_pa_status -server NCO_PA -user repino -password AGFFBIBLFLFJFIGL;
	"""
	nco_pa_cmd = NETCOOL_HOME + "nco_pa_status -server " + PA_NAME + " -user " + PA_USER + " -password " + PA_PASS
	(inpipe, outpipe, errpipe) = os.popen3(nco_pa_cmd)
	nco_pa_status_out = outpipe.readlines()
	nco_pa_status_err = errpipe.readlines()
	if len(nco_pa_status_out) > 3 and nco_pa_status_out[1].startswith ("Service Name"):
		status_pos = nco_pa_status_out[1].find("Status")
		for line in nco_pa_status_out:
			if line.find(probe_pa_name) != -1:
				status = line[status_pos:].split(' ')[0].strip()
	else:
		print "stdout: " + str(nco_pa_status_out) + "\nstderr:" +str(nco_pa_status_err) 
		status = "CMD_ERROR"
	return status

def probe_manage (probe_pa_name, action):
	"""
	Probe stop/start, function usage: probe_manage(PROBE_PA_NAME, 'stop'|'start')
	cmd examples:
	C:\IBM\tivoli\netcool\omnibus\bin\nco_pa_start -process "EIF probe" -user repino -password  AGFFBIBLFLFJFIGL
	C:\IBM\tivoli\netcool\omnibus\bin\nco_pa_stop -process "EIF probe" -user repino -password  AGFFBIBLFLFJFIGL
	"""
	nco_pa_cmd = NETCOOL_HOME + 'nco_pa_'+action+' -process "' + PROBE_PA_NAME + '" -user ' + PA_USER + " -password " + PA_PASS
	(inpipe, outpipe, errpipe) = os.popen3(nco_pa_cmd)
	nco_pa_status_out = outpipe.readlines()
	nco_pa_status_err = errpipe.readlines()
	if nco_pa_status_err:
		print "stdout: " + str(nco_pa_status_out) + "\nstderr:" +str(nco_pa_status_err) 
		status = "CMD_ERROR"
	else:
		status = "OK"
	return status

import time
def probe_restart (probe_pa_name):
	"""
	Probe restart
	"""
	if probe_status(probe_pa_name) == "RUNNING":
		probe_manage (probe_pa_name, 'stop')
		time.sleep(1)
		if probe_status(probe_pa_name) != "DEAD":
			time.sleep(30)
			print "long sleep"
	probe_manage (probe_pa_name, 'start')
	time.sleep(1)
	if probe_status(probe_pa_name) != "RUNNING":
		time.sleep(30)
		print "long sleep"
	return probe_status(probe_pa_name) 
		
import shutil
def probe_lookup_update (probe_pa_name, xls_file_path, lookup_file_path):
	lookup_file_backup_path = lookup_file_path[:-4]+"_orig.txt"
	shutil.copyfile(lookup_file_path, lookup_file_backup_path)
	xls_to_lookup(xls_file_path, lookup_file_path)
	probe_status = probe_restart (probe_pa_name)
	if (probe_status != "RUNNING"):
		shutil.copyfile(lookup_file_backup_path, lookup_file_path)
		print "Lookup update fail, use old lookup file"
		probe_status = probe_restart (probe_pa_name)
	return probe_status

import sys	
if __name__=='__main__':
	if len(sys.argv) < 2:
		print "Generate lookup without updating original.\n"
		xls_to_lookup (XLS_FILE_PATH)
	elif sys.argv[1] == "restart":
		print "Restart probe.\n"
		status = probe_restart (PROBE_PA_NAME)
		print "Current probe status is: %s" %status	
	elif sys.argv[1] == "update":
		print "Update lookup and restart probe.\n"
		status = probe_lookup_update (PROBE_PA_NAME, XLS_FILE_PATH, LOOKUP_FILE_PATH)
		print "Current probe status is: %s" %status	
	else:
		print "Wrong arguments!\n"